<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import jyglService from '@/api/jygl'
import zzjgService from '@/api/zzjg'
import { getFldm } from '@/utils/get-fldm'
import treeSelect from '@/components/tree-select-edl/index.vue'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
const mainStore = useMainStore()
const isLoading = ref()
const formRef = ref()
const dalyTreeRef = ref()
// 生命周期
const sjdwList = ref()

onMounted(() => {
  zzjgService.getDwbm({ dwbm: mainStore.userInfo.dwbm }).then((res: any) => {
    sjdwList.value = res.data.data
  })
  // 借阅目的分类代码
  getJymd()
  // 借阅类型分类代码
  getJylx()
})

// 借阅方式分类代码
const jyfsList = ref()
const getJyfs = async () => {
  jyfsList.value = await getFldm('gd043')
  form.value.jyfsdm = jyfsList.value[0].dm
  form.value.jyfsmc = jyfsList.value[0].mc
}
// 借阅目的分类代码
const jymdList = ref()
const getJymd = async () => {
  jymdList.value = await getFldm('gd044')
}
// 借阅类型分类代码
const jylxList = ref()
const getJylx = async () => {
  jylxList.value = await getFldm('gd048')
}

/*
 * 提交申请（包含修改、续借）
 */
// 保存借阅申请入参
const form = ref<any>({
  jysqbh: '', // 借阅申请数据编号(新增不传)
  bmsah: '', // 部门受案号
  jyrdwbm: mainStore.userInfo.dwbm, // 借阅单位编码
  jyrdwmc: mainStore.userInfo.dwmc, // 借阅单位名称
  sjdwbm: '', // 数据所属单位编码
  sjdwmc: '', // 数据所属单位名称
  jyrbmbm: mainStore.userInfo.bmbm, // 借阅人部门编码
  jyrbmmc: mainStore.userInfo.bmmc, // 借阅人部门名称
  jyrbh: mainStore.userInfo.ryid, // 借阅人编号
  jyrxm: mainStore.userInfo.xm, // 借阅人姓名
  jyfsdm: '', // 借阅方式代码
  jyfsmc: '', // 借阅方式名称
  jyts: '', // 借阅天数
  syfsdm: '', // 使用方式代码
  syfsmc: '', // 使用方式名称(打印,下载，查看)
  jymddm: '', // 借阅目的代码
  jymdmc: '', // 借阅目的名称
  jylxdm: '', // 借阅类型代码
  jylxmc: '', // 借阅类型名称
  cxdanr: '', // 查询档案内容
  jymx: '', // 借阅明细
  sfky: 'N', // 是否跨院不能为空
})

const rules = ref<FormRules>({
  sjdwmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  syfsdm: [
    {
      required: true,
      message: '请选择',
      trigger: 'submit',
    },
  ],
  jymdmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  cxdanr: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],
  jyts: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  jylxmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  jyfsmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
})

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    form.value.syfsdm = checkbox1.value.map((item) => (item ? '1' : '0')).join(',')
    let newArr: any = []
    checkbox1.value.forEach((item, index) => {
      if (item) {
        if (index === 0) {
          newArr.push('查看')
        }
        if (index === 1) {
          newArr.push('下载')
        }
        if (index === 2) {
          newArr.push('打印')
        }
      }
      return ''
    })
    form.value.syfsmc = newArr.join('+')
    if (valid) {
      let paramsList: any = null
      //   let multipleSelectionList = multipleSelection.value.filter((item: any) => item.cj)
      if (tabsLabel.value === '诉讼档案') {
        let filterList = multipleSelection.value.map((item: any) => {
          return {
            ajbh: item.ajbh,
            dabh: item.dabh,
            bmsah: item.bmsah,
            dwbm: mainStore.userInfo.dwbm,
            dwmc: mainStore.userInfo.dwmc,
            jydalxdm: rowtableData.value.jylxdm,
            jydalxmc: rowtableData.value.jylxmc,
            jysjbh: item.dm,
            jysjlxdm: 'gd0410001',
            jysjlxmc: '案件',
            sjbh: item.dm,
            sjdwbm: item.cbdwbm,
            sjdwmc: item.cbdwmc,
          }
        })

        paramsList = {
          ...form.value,
          jyrbh: mainStore.userInfo.ryid,
          jysjList: filterList,
        }
      } else {
        let filterList = multipleSelection.value.map((el: any) => {
          return {
            ajbh: el.ajbh,
            dabh: el.dabh,
            bmsah: el.bmsah,
            dwbm: mainStore.userInfo.dwbm,
            dwmc: mainStore.userInfo.dwmc,
            jydalxdm: rowtableData.value.jylxdm,
            jydalxmc: rowtableData.value.jylxmc,
            jysjbh: el.mlbh,
            jysjlxdm: 'gd0410004',
            jysjlxmc: '视频',
            sjbh: el.mlbh,
            sjdwbm: el.dwbm,
            sjdwmc: el.ljdw,
            // ajbh: el.ajbh,
            // dabh: el.dabh,
            // jydalxdm: rowtableData.value.jylxdm,
            // jydalxmc: rowtableData.value.jylxmc,
            // jyrbh: mainStore.userInfo.tyywid,
            // jyrxm: mainStore.userInfo.xm,
            // jysjbh: el.mlbh,
            // jysjlxdm: 'gd0410004',
            // jysjlxmc: '视频',
            // sjdwbm: el.ljdwbm,
            // sjdwmc: el.ljdw,
          }
        })
        paramsList = {
          ...form.value,
          jyrbh: mainStore.userInfo.ryid,
          jysjList: filterList,
        }
      }

      const params = paramsList
      jyglService
        .saveJysq(params)
        .then((res) => {
          if (res.data.czjg) {
            ElMessage.success('添加成功')
            closeDialog()
          }
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

/*
 * 移除目录
 */
const ycml = () => {
  ElMessageBox.confirm('确定移除选中数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let val: any = multipleSelection.value
    if (val) {
      for (let i = 0; i < val.length; i++) {
        tableData.value = tableData.value.filter((v: any) => v.id !== val[i]?.dabh)
      }
    }
    ElMessage.success('移除成功')
  })
}

/*
 * 打开弹窗
 */
//
const dialogTitle = ref()
const tabsLabel = ref()
const tableData = ref()
const rowtableData = ref()
const dialogVisible = ref(false)
const openDialog = (title: string, tabTitle: string, checkData: any, rowData: any) => {
  if (title === 'edit') {
    dialogTitle.value = '修改借阅申请'
  } else {
    dialogTitle.value = '新增借阅申请'
  }
  tabsLabel.value = tabTitle
  checkData.forEach((element: any) => {
    if (element.children && element.children.length > 0) {
      element.children = TreeUtilDTO.getTreeData(element.children, 'dm', 'fdm')
    }
  })
  tableData.value = checkData
  rowtableData.value = rowData
  // 借阅方式分类代码
  getJyfs()
  dialogVisible.value = true
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  dialogVisible.value = false
}

const rightSmall = ref<boolean>(false)
// 是否按下
const dragFlag = ref<boolean>(false)
const dragstart = () => {
  dragFlag.value = true
}

const moveLenHeight = ref<number>(0)
const dragRight = (e: any) => {
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && window.innerHeight - e.clientY - 26 <= 200) {
    moveLenHeight.value = 200
  } else if (e.clientY && window.innerHeight - e.clientY - 26 >= 400) {
    moveLenHeight.value = 400
  } else {
    moveLenHeight.value = window.innerHeight - e.clientY - 26
  }
}

const dragend = () => {
  dragFlag.value = false
}

const multipleSelection = ref([])
// 表格复选框
const handleSelectionChange = (row: any) => {
  multipleSelection.value = row
}

// 借阅方式代码
const jyfsChange = (index: number) => {
  form.value.jyfsmc = jyfsList.value[index].mc
  form.value.jyfsdm = jyfsList.value[index].dm
}
// 借阅类型代码
const jylxChange = (val: any) => {
  let obj: any = {}
  obj = jylxList.value.find((item: any) => {
    return item.dm === val //筛选出匹配数据，这里的value是你遍历数组每一项的value，如果没有对后台返回的数据做处理，一般为id
  })
  form.value.jylxmc = obj.mc
  form.value.jylxdm = obj.dm
}

// 借阅目的
const jymdChange = (index: number) => {
  form.value.jymdmc = jymdList.value[index].mc
  form.value.jymddm = jymdList.value[index].dm
}

const checkNodes = ref([])
const checkbox1 = ref([false, false, false])

const check = (data: any, checks: any) => {
  checkNodes.value = checks.checkedNodes
}

const nodeChange = (data: any, node: any) => {
  form.value.sjdwbm = node.dwbm
  form.value.sjdwmc = node.dwmc
}

watch(
  () => checkbox1,
  (val) => {
    if (checkbox1.value[1] || checkbox1.value[2]) {
      checkbox1.value[0] = true
    }
  },
  {
    deep: true,
  },
)

const syfsDisabled = computed(() => {
  if (form.value.jyfsdm === 'gd0430001') {
    return false
  } else {
    return true
  }
})

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1200px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <el-form ref="formRef" label-width="auto" :model="form" :rules="rules" style="height: 330px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="借阅单编号">
            <el-input v-model="form.jysqbh" placeholder="请输入" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请日期" style="width: 100%">
            <el-date-picker
              style="width: 100%"
              v-model="form.sqrq"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
            />
            <!-- <el-input v-model="form.nd" placeholder="请输入" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅单位">
            <el-input v-model="form.jyrdwmc" disabled placeholder="请输入" />
            <!-- <el-select
              v-model="form.jyrdwmc"
              clearable
              disabled
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(zrritem, index) in jyrdwList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅人">
            <el-input v-model="form.jyrxm" disabled placeholder="请输入" />
            <!-- <el-date-picker
              width="100%"
              v-model="form.zrz"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅人部门" disabled style="width: 100%">
            <el-input v-model="form.jyrbmmc" disabled placeholder="请输入" />
            <!-- <el-select
              v-model="form.jyrbmmc"
              clearable
              placeholder="请选择"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="(zrritem, index) in jyrbmList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅人电话" style="width: 100%">
            <el-input v-model="form.jyrdh" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅人邮箱" style="width: 100%">
            <el-input v-model="form.jyryx" placeholder="请输入" disabled />
            <!-- <el-select v-model="form.wjgs" clearable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="zrritem in wjgsList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="zrritem.dm"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅方式" prop="jyfsmc" style="width: 100%">
            <el-select
              v-model="form.jyfsmc"
              clearable
              placeholder="请选择"
              style="width: 100%"
              @change="jyfsChange"
            >
              <el-option
                v-for="(zrritem, index) in jyfsList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select>
            <!-- <el-input v-model="form.lzdwmc" placeholder="请输入录制单位" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅天数" prop="jyts">
            <el-select v-model="form.jyts" clearable placeholder="请选择" style="width: 100%">
              <el-option label="14" value="14"> </el-option>
              <el-option label="30" value="30"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="档案所属院" prop="sjdwmc" style="width: 100%">
            <tree-select
              style="width: 100%"
              :multiple="false"
              v-model="form.sjdwmc"
              searchPlaceholder="请输入"
              :treeProps="{
                children: 'children',
                label: 'dwmc',
              }"
              :isLeafNode="false"
              node-key="dwbm"
              @nodeChange="nodeChange"
              :options="sjdwList"
            ></tree-select>
            <!-- <el-select v-model="form.sjdwmc" clearable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="zrritem in sjdwList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="zrritem.dm"
              >
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="使用方式" :prop="form.jyfsdm === 'gd0430001' ? 'syfsdm' : ''">
            <el-checkbox v-model="checkbox1[0]" label="查看" :disabled="syfsDisabled"></el-checkbox>
            <el-checkbox v-model="checkbox1[1]" label="下载" :disabled="syfsDisabled"></el-checkbox>
            <el-checkbox v-model="checkbox1[2]" label="打印" :disabled="syfsDisabled"></el-checkbox>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="是否跨院" prop="sfky">
            <el-radio-group v-model="form.sfky">
              <el-radio value="Y">是</el-radio>
              <el-radio value="N">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="借阅类型" prop="jylxmc">
            <el-radio-group v-model="form.jylx" @change="jylxChange">
              <el-radio v-for="zrritem in jylxList" :key="zrritem.dm" :value="zrritem.dm">{{
                zrritem.mc
              }}</el-radio>
              <!-- <el-radio value="N">跨院</el-radio> -->
            </el-radio-group>
            <!-- <el-select
              v-model="form.jylx"
              clearable
              placeholder="请选择"
              style="width: 100%"
              @change="jylxChange"
            > -->

            <!-- <el-option
                v-for="(zrritem, index) in jylxList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              > -->
            <!-- </el-option> -->
            <!-- </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借阅目的" prop="jymdmc" style="width: 100%">
            <el-select
              v-model="form.jymdmc"
              clearable
              placeholder="请选择"
              style="width: 100%"
              @change="jymdChange"
            >
              <el-option
                v-for="(zrritem, index) in jymdList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="查档内容" prop="cxdanr" style="width: 100%">
            <el-input
              type="textarea"
              :row="5"
              maxlength="500"
              v-model="form.cxdanr"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--拖动div-->
    <div
      class="table-drag-box"
      :draggable="true"
      title="可上下拖动"
      @dragstart="dragstart()"
      @dragend="dragend()"
      @drag="dragRight($event)"
    >
      <div class="dragImg">
        <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
      </div>
    </div>

    <div
      class="right-bottom"
      :class="{ small: rightSmall }"
      :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
    >
      <div class="right-img" @click="rightSmall = !rightSmall">
        <img src="@/assets/images/zsq.png" alt="" v-if="!rightSmall" />
        <img src="@/assets/images/ysq.png" alt="" v-else-if="rightSmall" />
      </div>
      <div class="delete-button">
        <el-button type="primary" @click="ycml" :disabled="!multipleSelection.length"
          >移除</el-button
        >
      </div>
      <div class="content-tabs">
        <el-tabs type="card">
          <!--  -->
          <el-tab-pane :label="tabsLabel" lazy>
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              highlight-current-row
              row-key="dabh"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <template v-if="tabsLabel == '诉讼档案'">
                <el-table-column type="expand">
                  <template #default="props">
                    <el-tree
                      ref="dalyTreeRef"
                      :data="props.row.children"
                      show-checkbox
                      :check-strictly="false"
                      :props="{ label: 'mc', children: 'children' }"
                      node-key="dm"
                      highlight-current
                      @check="check"
                    >
                    </el-tree>
                  </template>
                </el-table-column>
                <el-table-column prop="dh" label="档号" show-overflow-tooltip />
                <el-table-column prop="ajmc" label="案件名称" />
                <el-table-column prop="bmsah" label="部门受案号" />
                <el-table-column prop="dsr" label="当事人" />
                <el-table-column prop="ay" label="案由" />
                <el-table-column prop="jcg" label="检察官" />
                <el-table-column prop="cbdwmc" label="档案所属院" />
              </template>
              <template v-if="tabsLabel == '视频档案'">
                <el-table-column prop="dh" label="档号" width="200" />
                <el-table-column prop="tm" label="题名" />
                <el-table-column prop="splx" label="视频类型" />
                <el-table-column prop="lzz" label="录制者" />
                <el-table-column prop="lzrq" label="录制日期" />
                <el-table-column prop="ljdw" label="档案所属院" />
              </template>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit(formRef)" :loading="isLoading">提交</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.delete-button {
  padding-bottom: 10px;
}

.right-bottom {
  height: 400px;
  border-top: 1px solid #dae4f1;
  position: relative;
  overflow-y: auto;
  padding-top: 10px;
  &.small {
    height: 10px !important;
    border: none !important;
  }
  .right-img {
    z-index: 9;
    cursor: pointer;
    position: absolute;
    left: calc(50% - 4px);
    top: -24px;
    transform: rotate(-90deg);
  }
}

.search-drag-box {
  margin: 0 1px;
  flex-shrink: 0;
  width: 10px;
  height: 100%;
  cursor: col-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;

  .dragImg {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
}
.table-drag-box {
  margin: 1px 0;
  flex-shrink: 0;
  height: 10px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;

  .dragImg {
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
</style>
